from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel, 
                               QFrame, QGridLayout)
from PySide6.QtGui import QFont, QColor, QPainter, QPen, QBrush
from PySide6.QtCore import Qt, QRectF, QPointF

from database.db_manager import DBManager

class StatsWidget(QWidget):
    """学习统计界面"""
    
    def __init__(self, db_manager: DBManager, parent=None):
        super().__init__(parent)
        self.db_manager = db_manager
        self.init_ui()
        
    def init_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)
        
        # 创建标题
        title_label = QLabel("学习统计")
        title_label.setStyleSheet("font-size: 24px; font-weight: bold; margin: 10px 0;")
        layout.addWidget(title_label, alignment=Qt.AlignCenter)
        
        # 创建统计卡片区域
        stats_layout = QGridLayout()
        stats_layout.setSpacing(20)
        
        # 总单词数卡片
        self.total_words_card = self.create_stats_card("总单词数", "0")
        stats_layout.addWidget(self.total_words_card, 0, 0)
        
        # 已掌握卡片
        self.mastered_card = self.create_stats_card("已掌握", "0", "#34c759")
        stats_layout.addWidget(self.mastered_card, 0, 1)
        
        # 学习中卡片
        self.learning_card = self.create_stats_card("学习中", "0", "#ffcc00")
        stats_layout.addWidget(self.learning_card, 0, 2)
        
        # 今日复习卡片
        self.today_review_card = self.create_stats_card("今日复习", "0", "#0071e3")
        stats_layout.addWidget(self.today_review_card, 1, 0)
        
        # 总复习次数卡片
        self.total_review_card = self.create_stats_card("总复习次数", "0", "#af52de")
        stats_layout.addWidget(self.total_review_card, 1, 1)
        
        # 连续学习天数卡片
        self.streak_card = self.create_stats_card("连续学习", "0 天", "#ff9500")
        stats_layout.addWidget(self.streak_card, 1, 2)
        
        layout.addLayout(stats_layout)
        
        # 创建学习趋势图表
        trend_frame = QFrame()
        trend_frame.setStyleSheet("background-color: white; border-radius: 10px; padding: 10px;")
        trend_layout = QVBoxLayout(trend_frame)
        
        trend_label = QLabel("学习趋势")
        trend_label.setStyleSheet("font-size: 18px; font-weight: bold; margin-bottom: 10px;")
        trend_layout.addWidget(trend_label)
        
        self.chart_widget = ChartWidget(self.db_manager)
        trend_layout.addWidget(self.chart_widget)
        
        layout.addWidget(trend_frame)
        
        layout.addStretch()
        
        # 刷新数据
        self.refresh_data()
        
    def create_stats_card(self, title: str, value: str, color: str = "#0071e3") -> QFrame:
        """创建统计卡片"""
        card = QFrame()
        card.setStyleSheet(f'''
            QFrame {{
                background-color: white;
                border-radius: 12px;
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1)
            }}
        ''')
        
        layout = QVBoxLayout(card)
        
        title_label = QLabel(title)
        title_label.setStyleSheet("font-size: 14px; color: #6e6e73;")
        layout.addWidget(title_label)
        
        value_label = QLabel(value)
        value_label.setStyleSheet(f"font-size: 28px; font-weight: bold; color: {color}; margin-top: 5px;")
        layout.addWidget(value_label)
        
        return card
        
    def refresh_data(self):
        """刷新统计数据"""
        try:
            # 获取统计数据
            stats = self.get_status_summary()
            
            # 更新卡片数据
            self.total_words_card.findChildren(QLabel, "", Qt.FindChildOption.FindChildrenRecursively)[1].setText(str(stats['total']))
            self.mastered_card.findChildren(QLabel, "", Qt.FindChildOption.FindChildrenRecursively)[1].setText(str(stats['mastered']))
            self.learning_card.findChildren(QLabel, "", Qt.FindChildOption.FindChildrenRecursively)[1].setText(str(stats['learning']))
            self.today_review_card.findChildren(QLabel, "", Qt.FindChildOption.FindChildrenRecursively)[1].setText(str(stats['today_review']))
            self.total_review_card.findChildren(QLabel, "", Qt.FindChildOption.FindChildrenRecursively)[1].setText(str(stats['total_review']))
            self.streak_card.findChildren(QLabel, "", Qt.FindChildOption.FindChildrenRecursively)[1].setText(f"{stats['streak']} 天")
            
            # 刷新图表
            self.chart_widget.refresh_data()
        except Exception as e:
            print(f"刷新统计数据失败: {e}")
            # 显示错误信息但不中断程序
            self.total_words_card.findChildren(QLabel, "", Qt.FindChildOption.FindChildrenRecursively)[1].setText("加载失败")
            
    def get_status_summary(self):
        """获取单词状态统计摘要"""
        try:
            # 获取总单词数和掌握程度统计
            conn = self.db_manager._connect()
            cursor = conn.cursor()
            
            # 总单词数
            cursor.execute('SELECT COUNT(*) FROM words')
            total = cursor.fetchone()[0]
            
            # 按掌握程度统计
            cursor.execute('SELECT mastery_level, COUNT(*) FROM words GROUP BY mastery_level')
            status_counts = {0: 0, 1: 0, 2: 0}
            for level, count in cursor.fetchall():
                if level in status_counts:
                    status_counts[level] = count
                    
            # 今日复习次数
            cursor.execute('''
            SELECT words_reviewed FROM learning_stats 
            WHERE date = CURRENT_DATE
            ''')
            today_review = cursor.fetchone()
            today_review_count = today_review[0] if today_review else 0
            
            # 总复习次数
            cursor.execute('SELECT SUM(review_count) FROM words')
            total_review = cursor.fetchone()[0] or 0
            
            # 获取连续学习天数
            streak = self.db_manager.get_streak_days()
            
            conn.close()
            
            return {
                'total': total,
                'unlearned': status_counts[0],
                'learning': status_counts[1],
                'mastered': status_counts[2],
                'today_review': today_review_count,
                'total_review': total_review,
                'streak': streak
            }
            
        except Exception as e:
            print(f"获取状态统计失败: {e}")
            return {'total': 0, 'unlearned': 0, 'learning': 0, 'mastered': 0, 
                    'today_review': 0, 'total_review': 0, 'streak': 0}

class ChartWidget(QWidget):
    """学习趋势图表组件"""
    
    def __init__(self, db_manager: DBManager, parent=None):
        super().__init__(parent)
        self.db_manager = db_manager
        self.data = []
        self.setMinimumHeight(200)
        
    def refresh_data(self):
        """刷新图表数据"""
        try:
            # 获取过去7天的学习数据
            conn = self.db_manager._connect()
            cursor = conn.cursor()
            
            cursor.execute('''
            SELECT date, words_reviewed 
            FROM learning_stats 
            ORDER BY date DESC 
            LIMIT 7
            ''')
            
            self.data = cursor.fetchall()
            self.data.reverse()  # 按日期升序排列
            conn.close()
            
            self.update()  # 触发重绘
        except Exception as e:
            print(f"刷新图表数据失败: {e}")
        
    def paintEvent(self, event):
        """绘制图表"""
        if not self.data:
            # 没有数据时显示提示
            painter = QPainter(self)
            painter.drawText(self.rect(), Qt.AlignCenter, "暂无学习数据")
            return
            
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        
        # 绘制区域
        rect = self.rect()
        margin = 40
        chart_rect = QRectF(margin, margin, rect.width() - 2*margin, rect.height() - 2*margin)
        
        # 绘制坐标轴
        pen = QPen(QColor(0, 0, 0, 100), 1)
        painter.setPen(pen)
        painter.drawRect(chart_rect)
        
        # 绘制网格线
        pen.setStyle(Qt.DashLine)
        painter.setPen(pen)
        
        # Y轴网格
        y_ticks = 5
        for i in range(1, y_ticks):
            y = chart_rect.top() + (chart_rect.height() * i / y_ticks)
            painter.drawLine(chart_rect.left(), y, chart_rect.right(), y)
            
        # X轴网格
        x_ticks = len(self.data) - 1
        for i in range(1, x_ticks):
            x = chart_rect.left() + (chart_rect.width() * i / x_ticks)
            painter.drawLine(x, chart_rect.top(), x, chart_rect.bottom())
            
        # 绘制数据点和线
        if len(self.data) < 2:
            return
            
        # 找出最大值用于缩放
        max_reviews = max([row[1] for row in self.data]) if self.data else 1
        scale = chart_rect.height() / max_reviews if max_reviews > 0 else 1
        
        # 绘制数据线
        pen = QPen(QColor(0, 113, 227), 2)
        painter.setPen(pen)
        
        points = []
        for i, (date, count) in enumerate(self.data):
            x = chart_rect.left() + (chart_rect.width() * i / (len(self.data) - 1))
            y = chart_rect.bottom() - (count * scale)
            points.append(QPointF(x, y))
            
            # 绘制数据点
            painter.setBrush(QBrush(QColor(0, 113, 227)))
            painter.drawEllipse(x - 4, y - 4, 8, 8)
            
            # 绘制日期标签
            date_str = date.split('-')[-2] + '/' + date.split('-')[-1]
            painter.drawText(x - 15, chart_rect.bottom() + 20, date_str)
            
            # 绘制数值标签
            painter.drawText(x - 10, y - 10, str(count))
            
        # 绘制数据线
        for i in range(len(points) - 1):
            painter.drawLine(points[i], points[i+1])